package com.ruoyi.zsyh.controller.applet.agent;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.ZtreeString;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.zsyh.domain.*;
import com.ruoyi.zsyh.service.*;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 产品Controller
 * 
 * @author yuexl
 * @date 2021-12-08
 */
@Controller
@RequestMapping("/applet/zsyh/parts")
public class ZsyhPlatformPartsAppletController extends BaseController
{

    @Autowired
    private IZsyhPlatformPartsService zsyhPlatformPartsService;

    @Autowired
    private IZsyhPlatformPartsattributeService zsyhPlatformPartsattributeService;

    @Autowired
    private IZsyhPlatformPartstypeService zsyhPlatformPartstypeService;

    @Autowired
    private IZsyhAgentAddressService zsyhAgentAddressService;

    @Autowired
    private IZsyhAgentOrderService zsyhAgentOrderService;

    @Autowired
    private IZsyhAgentOrderRelService zsyhAgentOrderRelService;

    @Autowired
    private IZsyhAgentPartsService zsyhAgentPartsService;

    @Autowired
    private IZsyhAgentInfoService zsyhAgentInfoService;

    @Autowired
    private IZsyhPartsSalesService zsyhPartsSalesService;

    @Autowired
    private IZsyhPlatformFactoryService zsyhPlatformFactoryService;

    @Autowired
    private IZsyhPlatformPartsCheckService zsyhPlatformPartsCheckService;

    @Autowired
    private IZsyhUserRepairstoreService zsyhUserRepairstoreService;

    @Autowired
    private IZsyhAgentCooperateService zsyhAgentCooperateService;

    @Autowired
    private CommonRpc commonRpc;

    /**
     * 获取产品分类
     * @param pid
     * @return
     */
    @RequestMapping("/getPartsTypeByPid")
    @ResponseBody
    public AjaxResult getPartsTypeByPid(String pid){
        pid = EmptyUtils.isEmpty(pid)?"0":pid;
        ZsyhPlatformPartstype type = new ZsyhPlatformPartstype();
        type.setpId(pid);
        return AjaxResult.success("获取成功", zsyhPlatformPartstypeService.selectZsyhPlatformPartstypeList(type));
    }

    /**
     * 获取匹配鉴定权产品列表
     * @param storeId
     * @return
     */
    @RequestMapping("/getPartsListCheckByStoreId")
    @ResponseBody
    public AjaxResult getPartsListCheckByStoreId(String userId, String storeId){
        if(EmptyUtils.isEmpty(storeId)){
            ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);
            storeId = store.getId();
        }
        List<Map> list = zsyhPlatformPartsService.getPartsListCheckByStoreId(storeId);
        return AjaxResult.success("获取成功", list);
    }

    /**
     * 提交匹配鉴定权
     * @param storeId
     * @param partsIds 多个产品id用英文逗号拼接
     * @return
     */
    @RequestMapping("/savePartsCheck")
    @ResponseBody
    @Transactional
    public AjaxResult savePartsCheck(String userId, String storeId, String partsIds){
        if(EmptyUtils.isEmpty(storeId)){
            ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);
            storeId = store.getId();
        }
        zsyhPlatformPartsCheckService.deleteZsyhPlatformPartsCheckByStoreId(storeId);//删除之前的鉴定权
        if(EmptyUtils.isNotEmpty(partsIds)){
            String[] _partsIds = partsIds.split(",");
            List<ZsyhPlatformPartsCheck> list = new ArrayList<>();
            for(String a:_partsIds){
                ZsyhPlatformPartsCheck check = new ZsyhPlatformPartsCheck();
                check.setPartsId(a);
                check.setStoreId(storeId);
                check.setCreateTime(new Date());
                list.add(check);
            }
            zsyhPlatformPartsCheckService.insertZsyhPlatformPartsCheckBatch(list);
        }
        return AjaxResult.success("成功");
    }



    /**
     * 获取产品列表
     * @param type 用户类型（1普通客户2配件店3维修师傅 4电器店）
     * @param typeId
     * @return
     */
    @RequestMapping("/getPartsList")
    @ResponseBody
    public AjaxResult getPartsList(String agentId, String typeId, String isHot, String name, String type, String pageNum, String pageSize){
        ZsyhPlatformParts parts = new ZsyhPlatformParts();
        parts.setPartsType(typeId);
        parts.setIsHotPush(isHot);
        parts.setPartsName(name);
        parts.setOperateType("search");
        if("1".equals(type) || "3".equals(type)){
            parts.setIsShowWorker("1");
        }else if("2".equals(type) || "4".equals(type)){
            parts.setIsShowWorker("1");
        }else if("0".equals(type)){
            parts.setIsShowProvince("1");
        }else {
            parts.setIsShowProvince("1");
        }
        Map map = new HashedMap();
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }

        map.put("agentId", agentId);
        parts.setParams(map);
        List<ZsyhPlatformParts> list = zsyhPlatformPartsService.selectZsyhPlatformPartsList(parts);
        return AjaxResult.success("获取成功", list);
    }

    /**
     * 获取产品列表 -- 大区会长
     * @param type 用户类型（1普通客户2配件店3维修师傅 4电器店）
     * @param typeId
     * @return
     */
    @RequestMapping("/getPartsListByAgentId")
    @ResponseBody
    public AjaxResult getPartsListByAgentId(String agentId, String typeId, String isHot, String name, String type, String pageNum, String pageSize){
        if(EmptyUtils.isEmpty(agentId)){
            return AjaxResult.error("暂未登录");
        }
        ZsyhPlatformParts parts = new ZsyhPlatformParts();
        parts.setPartsType(typeId);
        parts.setIsHotPush(isHot);
        parts.setPartsName(name);
        parts.setOperateType("search");
        if("1".equals(type) || "3".equals(type)){
            parts.setIsShowWorker("1");
        }else if("2".equals(type) || "4".equals(type)){
            parts.setIsShowWorker("1");
        }else if("0".equals(type)){
            parts.setIsShowProvince("1");
        }else {
            parts.setIsShowProvince("1");
        }
        Map map = new HashedMap();
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }

        map.put("agentId", agentId);
        parts.setParams(map);
        List<ZsyhPlatformParts> list = zsyhPlatformPartsService.selectZsyhPlatformPartsList(parts);
        return AjaxResult.success("获取成功", list);
    }


    /**
     * 获取产品列表 -- 业务员
     * @param typeId
     * @return
     */
    @RequestMapping("/getPartsListByBusiness")
    @ResponseBody
    public AjaxResult getPartsListByBusiness(String typeId, String isHot, String name, String pageNum, String pageSize){
        ZsyhPlatformParts parts = new ZsyhPlatformParts();
        parts.setPartsType(typeId);
        parts.setIsHotPush(isHot);
        parts.setPartsName(name);
        parts.setOperateType("search");
        parts.setIsShowProvince("1");

        Map map = new HashedMap();
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        parts.setParams(map);
        List<ZsyhPlatformParts> list = zsyhPlatformPartsService.selectZsyhPlatformPartsList(parts);
        return AjaxResult.success("获取成功", list);
    }

    /**
     * 获取产品列表(大区获取合作产品时)
     * @param typeId
     * @return
     */
    @RequestMapping("/getPartsListAll")
    @ResponseBody
    public AjaxResult getPartsListAll(String agentId, String typeId, String name, String pageNum, String pageSize){
        ZsyhPlatformParts parts = new ZsyhPlatformParts();
        parts.setPartsType(typeId);
        parts.setPartsName(name);
        parts.setOperateType("search");
        parts.setIsShowProvince("1");

        Map map = new HashedMap();
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        map.put("populationSalesRatio", "1");
        parts.setParams(map);
        List<ZsyhPlatformParts> list = zsyhPlatformPartsService.selectZsyhPlatformPartsList(parts);
        return AjaxResult.success("获取成功", list);
    }

    /**
     * 获取规格列表
     * @return
     */
    @RequestMapping("/getPartsAttributeByPartsId")
    @ResponseBody
    public AjaxResult getPartsAttributeByPartsId(String partsId, String agentId){
        ZsyhAgentInfo agentInfo = zsyhAgentInfoService.selectZsyhAgentInfoById(agentId);
        if(agentInfo == null || "0".equals(agentInfo.getAgentValid())){
            return error(AjaxResult.Type.LOGOUT, "用户状态异常，请联系管理员");
        }
        ZsyhPlatformPartsattribute attribute = new ZsyhPlatformPartsattribute();
        attribute.setPartsId(partsId);
        attribute.setIsShowProvice("1");
        Map map = new HashMap();
        map.put("agentId", agentId);
        attribute.setParams(map);
        return AjaxResult.success("获取成功", zsyhPlatformPartsattributeService.selectZsyhPlatformPartsattributeList(attribute));
    }

    /**
     * 获取规格列表 -- 业务员他
     * @return
     */
    @RequestMapping("/getPartsAttributeBybusiness")
    @ResponseBody
    public AjaxResult getPartsAttributeBybusiness(String partsId){
        ZsyhPlatformPartsattribute attribute = new ZsyhPlatformPartsattribute();
        attribute.setPartsId(partsId);
        attribute.setIsShowProvice("1");
        return AjaxResult.success("获取成功", zsyhPlatformPartsattributeService.selectZsyhPlatformPartsattributeList(attribute));
    }

    /**
     * 获取此厂家下所有产品规格
     * @param factoryId
     * @return
     */
    @RequestMapping("/getPartsAttributeByFactoryId")
    @ResponseBody
    public AjaxResult getPartsAttributeByFactoryId(String factoryId, String partsId, String agentId){
        ZsyhAgentInfo agentInfo = zsyhAgentInfoService.selectZsyhAgentInfoById(agentId);
        if(agentInfo == null || "0".equals(agentInfo.getAgentValid())){
            return error(AjaxResult.Type.LOGOUT, "用户状态异常，请联系管理员");
        }

        boolean isReserve = false;// true可以预定 false不可以预定
        ZsyhPlatformParts parts = zsyhPlatformPartsService.selectZsyhPlatformPartsById(partsId);
        String partsType = parts.getPartsType();
        Map map = new HashMap();
        map.put("agentId", agentId);
        map.put("partsId", partsType);
        List<Map> agentCooperateList = zsyhAgentCooperateService.selectAgentCooperateByAgentId(map);
        if(!agentCooperateList.isEmpty()){//会长合作此产品，可以直接预定
            isReserve = true;
        }else{
            //会长未合作此产品，判断产品分类是否需要合作，不需要合作也可以预定
            ZsyhPlatformPartstype zsyhPlatformPartstype = zsyhPlatformPartstypeService.selectZsyhPlatformPartstypeById(partsType);
            String populationSalesRatio = zsyhPlatformPartstype.getPopulationSalesRatio();
            if(EmptyUtils.isEmpty(populationSalesRatio)){
                isReserve = true;
            }else{
                Double populationSalesRatioDouble = Double.valueOf(populationSalesRatio);
                if(populationSalesRatioDouble <= 0){
                    isReserve = true;
                }
            }
        }


        ZsyhPlatformPartsattribute attribute = new ZsyhPlatformPartsattribute();
        map = new HashMap();
        map.put("agentId", agentId);
        map.put("factoryId", factoryId);
        map.put("partsId", partsId);
        map.put("partsIsShowProvice", "1");
        attribute.setParams(map);
        attribute.setPartsId(partsId);
        attribute.setIsShowProvice("1");
        ZsyhPlatformFactory factory = zsyhPlatformFactoryService.selectZsyhPlatformFactoryById(factoryId);
        List<ZsyhPlatformPartsattribute> list = zsyhPlatformPartsattributeService.selectZsyhPlatformPartsattributeList(attribute);
        factory.setAttributeList(list);
        factory.setIsReserve(isReserve);
        return AjaxResult.success("获取成功", factory);
    }

    /**
     * 提交预订单
     * @param factoryId
     * @return
     */
    @RepeatSubmit
    @RequestMapping("/submitReservation")
    @ResponseBody
    @Transactional
    public AjaxResult submitReservation(String addressId, String factoryId, String partsJson){

        ZsyhAgentAddress address = zsyhAgentAddressService.selectZsyhAgentAddressById(addressId);
        String agentId = address.getAgentId();
        ZsyhAgentInfo agentInfo = zsyhAgentInfoService.selectZsyhAgentInfoById(agentId);
        if(agentInfo == null || "0".equals(agentInfo.getAgentValid())){
            return error(AjaxResult.Type.LOGOUT, "用户状态异常，请联系管理员");
        }
        //解析产品json数据
        List<Map<String, Object>> list = JSON.parseObject(partsJson, new TypeReference<List<Map<String, Object>>>() {});
        List<ZsyhAgentOrderRel> relList = new ArrayList<>();
        //保存订单信息
        ZsyhAgentOrder order = new ZsyhAgentOrder();
        String id = IdWorker.getId();
        order.setId(id);
        order.setOrderState("1");
        order.setOrderName(address.getAddressName());
        order.setOrderPhone(address.getAddressPhone());
        order.setOrderAddress(address.getAddressPrivinceName() + address.getAddressCityName() + address.getAddressDistrictName() + " " + address.getAddressDetail());
        order.setAgentAddressId(addressId);
        order.setFactoryId(factoryId);
        order.setAgentId(address.getAgentId());
        order.setOrderState("1");
        Date date = new Date();
        double moneyAll = 0.00;
        String attributeIds = "";
        Map<String, String> map = new HashMap<>();
        for(Map<String, Object> a:list){//解析预定产品，并保存
            String attributeId = String.valueOf(a.get("attributeId"));
            String partsId = String.valueOf(a.get("partsId"));
            String count = String.valueOf(a.get("count"));
            BigDecimal price = new BigDecimal(String.valueOf(a.get("price")));

            ZsyhAgentOrderRel rel = ZsyhAgentOrderRel.getInstance();
            rel.setId(IdWorker.getId());
            rel.setOrderId(id);
            rel.setPartsId(partsId);
            rel.setAttributeId(attributeId);
            rel.setOrderCount(count);
            rel.setOrderSellCount(count);
            rel.setOrderPrice(price);
            rel.setOrderSellPrice(price);
            rel.setCreateTime(date);

            relList.add(rel);

            moneyAll += Double.valueOf(count) * price.doubleValue();

            attributeIds += attributeId + ",";//拼接规格id
            if(map != null && map.size() > 0){
                String numStr = map.get(attributeId);
                if(EmptyUtils.isNotEmpty(numStr)){
                    count = String.valueOf(Double.valueOf(count) + Double.valueOf(numStr));
                }
            }
            map.put(attributeId, count);
            map.put(attributeId + "_price", price.toString());
        }
        String dateString = DateUtils.getDate();
        Integer year = Integer.valueOf(dateString.substring(0,4));
        Integer month = Integer.valueOf(dateString.substring(5,7));
        List<ZsyhPartsSales> salesList = zsyhPartsSalesService.getPartsSalesList(year, month, attributeIds);
        List<ZsyhPartsSales> saveSalesList = new ArrayList<>();
        List<ZsyhPartsSales> updateSalesList = new ArrayList<>();
        for(ZsyhPartsSales a:salesList){
            String salesId = a.getId();
//            String factoryId = a.getFactoryId();
            String partsId = a.getPartsId();
            String attributeId = a.getAttributeId();
            ZsyhPartsSales sale = new ZsyhPartsSales();

            BigDecimal partsPrice = new BigDecimal(map.get(attributeId + "_price"));
            BigDecimal count = new BigDecimal(map.get(attributeId));

            if(salesId != null){
                BigDecimal bookNum = a.getBookNum();
                BigDecimal bookMoney = a.getBookMoney();
                BigDecimal deliveryNum = a.getDeliveryNum();
                bookNum = bookNum.add(count).setScale(2, BigDecimal.ROUND_HALF_UP);
                bookMoney = bookMoney.add(count.multiply(partsPrice).setScale(2, BigDecimal.ROUND_HALF_UP));
                sale.setId(salesId);
                sale.setBookNum(bookNum);
                sale.setBookMoney(bookMoney);
                updateSalesList.add(sale);
            }else{
                sale.setId(IdWorker.getId());
                sale.setFactoryId(factoryId);
                sale.setPartsId(partsId);
                sale.setBookNum(count.setScale(2, BigDecimal.ROUND_HALF_UP));
                sale.setBookMoney(sale.getBookNum().multiply(partsPrice).setScale(2, BigDecimal.ROUND_HALF_UP));
                sale.setDeliveryNum(BigDecimal.ZERO);
                sale.setDeliveryMoney(BigDecimal.ZERO);
                sale.setAttributeId(attributeId);
                sale.setPeriodYear(year);
                sale.setPeriodMonth(month);
                saveSalesList.add(sale);
            }
        }

        order.setOrderBeginMoney(new BigDecimal(String.valueOf(moneyAll)).setScale(2, BigDecimal.ROUND_HALF_UP));
        order.setOrderEndMoney(order.getOrderBeginMoney());
        order.setZsyhAgentOrderRelList(relList);
        zsyhAgentOrderService.insertZsyhAgentOrder(order);//保存订单信息 产品信息

        if(saveSalesList.size() > 0)zsyhPartsSalesService.insertZsyhPartsSalesBatch(saveSalesList);
        if(updateSalesList.size() > 0)zsyhPartsSalesService.updateZsyhPartsSalesBatch(updateSalesList);

        ZsyhPlatformFactory factory = zsyhPlatformFactoryService.selectZsyhPlatformFactoryById(factoryId);
        String factoryPhone = factory.getFactoryPhone();
        commonRpc.sendSmsAgentPartsOrder(factoryPhone);//下单成功，发送短信提醒

        return success("操作成功");

    }


    /**
     * 获取预定单列表
     * @param agentId
     * @param type 1当日预订单 2历史预订单
     * @param orderState 1待接单，2已接单，3已发货，4已结算  0全部
     * @return
     */
    @RequestMapping("/getReserveOrderList")
    @ResponseBody
    @Transactional
    public AjaxResult getReserveOrderList(String agentId, String type, String orderState, String pageNum, String pageSize){
        if(EmptyUtils.isEmpty(agentId)){
            return AjaxResult.error("暂未登录");
        }
        ZsyhAgentOrder order = new ZsyhAgentOrder();
        order.setAgentId(agentId);
        Map map = new HashMap();
        map.put("orderType", type);

        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        if("0".equals(orderState)){
            map.put("orderState", orderState);
        }else{
            order.setOrderState(orderState);
        }
        order.setParams(map);
        List<ZsyhAgentOrder> list = zsyhAgentOrderService.selectZsyhAgentOrderList(order);
        return success("操作成功", list);

    }

    /**
     * 获取预定单列表 -- 业务员
     * @param orderState 1待接单，2已接单，3已发货，4已结算  0全部
     * @return
     */
    @RequestMapping("/getReserveOrderListByBusiness")
    @ResponseBody
    @Transactional
    public AjaxResult getReserveOrderListByBusiness(String businessId, String orderState, String pageNum, String pageSize){
        ZsyhAgentOrder order = new ZsyhAgentOrder();
        Map map = new HashMap();

        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        if("0".equals(orderState)){
            map.put("orderState", orderState);
        }else{
            order.setOrderState(orderState);
        }
        order.setParams(map);
        List<ZsyhAgentOrder> list = zsyhAgentOrderService.selectZsyhAgentOrderList(order);
        return success("操作成功", list);

    }

    /**
     * 获取预定单详情
     * @param id
     * @return
     */
    @RequestMapping("/getReserveOrderDetails")
    @ResponseBody
    @Transactional
    public AjaxResult getReserveOrderDetails(String id){
        ZsyhAgentOrder order = zsyhAgentOrderService.selectZsyhAgentOrderById(id);
        return success("操作成功", order);

    }

    /**
     * 取消预订单
     * @param id
     * @return
     */
    @RequestMapping("/cancelOrder")
    @ResponseBody
    @Transactional
    public AjaxResult cancelOrder(String id){
        ZsyhAgentOrder _order = zsyhAgentOrderService.selectZsyhAgentOrderById(id);
        String createDate = DateUtils.dateTime(_order.getCreateTime());
        ZsyhAgentOrder order = new ZsyhAgentOrder();
        order.setId(id);
        order.setOrderState("0");
        zsyhAgentOrderService.updateZsyhAgentOrderAppLet(order);


        //start 订单取消，核算数据减少
        Integer year = Integer.valueOf(createDate.substring(0,4));
        Integer month = Integer.valueOf(createDate.substring(5,7));
        ZsyhAgentOrderRel rel = new ZsyhAgentOrderRel();
        rel.setOrderId(id);
        String attributeIds = "";
        Map<String, String> map = new HashMap<>();
        List<ZsyhAgentOrderRel> relList = zsyhAgentOrderRelService.selectZsyhAgentOrderRelList(rel);
        for(ZsyhAgentOrderRel a:relList){
            String attributeId = a.getAttributeId();
            String count = a.getOrderCount();
            String orderPrice = a.getOrderPrice().toString();
            attributeIds += attributeId + ",";//拼接规格id
            if(map != null && map.size() > 0){
                String numStr = map.get(attributeId);
                if(EmptyUtils.isNotEmpty(numStr)){
                    count = String.valueOf(Double.valueOf(count) + Double.valueOf(numStr));
                }
            }
            map.put(attributeId, count);
            map.put(attributeId + "_price", orderPrice);
        }
        List<ZsyhPartsSales> salesList = zsyhPartsSalesService.getPartsSalesList(year, month, attributeIds);
        List<ZsyhPartsSales> updateSalesList = new ArrayList<>();
        for(ZsyhPartsSales a:salesList){
            String salesId = a.getId();
//            String factoryId = a.getFactoryId();
//            String partsId = a.getPartsId();
            String attributeId = a.getAttributeId();
            String isCheck = a.getIsCheck();
            if("0".equals(isCheck)){
                ZsyhPartsSales sale = new ZsyhPartsSales();
                if(salesId != null){
                    BigDecimal partsPrice = new BigDecimal(map.get(attributeId + "_price"));
                    BigDecimal count = new BigDecimal(map.get(attributeId));

                    BigDecimal bookNum = a.getBookNum();
                    BigDecimal bookMoney = a.getBookMoney();
//                    BigDecimal deliveryNum = a.getDeliveryNum();
                    bookNum = bookNum.subtract(count).setScale(2, BigDecimal.ROUND_HALF_UP);
                    bookMoney = bookMoney.subtract(partsPrice.multiply(count)).setScale(2, BigDecimal.ROUND_HALF_UP);
                    if(bookNum.doubleValue() == 0 && a.getDeliveryNum().doubleValue() == 0){
                        zsyhPartsSalesService.deleteZsyhPartsSalesById(a.getId());
                    }else{
                        sale.setId(salesId);
                        sale.setBookNum(bookNum);
                        sale.setBookMoney(bookMoney);
                        updateSalesList.add(sale);
                    }
                }
            }
        }
        if(updateSalesList.size() > 0)zsyhPartsSalesService.updateZsyhPartsSalesBatch(updateSalesList);

        return success("操作成功", order);

    }


    /**
     * 确认结算
     * @param id
     * @return
     */
    @RequestMapping("/settleAccounts")
    @ResponseBody
    @Transactional
    public AjaxResult settleAccounts(String id){
        ZsyhAgentOrder order = new ZsyhAgentOrder();
        order.setId(id);
        order.setOrderState("4");
        zsyhAgentOrderService.updateZsyhAgentOrderAppLet(order);
        return success("操作成功", order);

    }

    /**
     * 批量上架到我的店铺
     * @return
     */
    @RequestMapping("/preserveMyParts")
    @ResponseBody
    @Transactional
    public AjaxResult preserveMyParts(String agentId, String partsId, String partsJson){
        //解析产品json数据
        List<Map<String, Object>> list = JSON.parseObject(partsJson, new TypeReference<List<Map<String, Object>>>() {});
        String attributeIds = "";
        Map<String, BigDecimal> map = new HashMap();
        for(Map<String, Object> a:list){
            String attributeId = String.valueOf(a.get("attributeId"));
            BigDecimal price = new BigDecimal(String.valueOf(a.get("price")));
            attributeIds += attributeId + ",";
            map.put(attributeId, price);
        }
        ZsyhPlatformParts p = zsyhPlatformPartsService.selectZsyhPlatformPartsById(partsId);//获取平台配件信息
        List<ZsyhPlatformPartsattribute> attList = zsyhPlatformPartsattributeService.getAttributeListByIds(attributeIds);//获取平台规格信息
        List<ZsyhAgentPartsattribute> arrList = new ArrayList<>();
        String partsIdNew = IdWorker.getId();
        Date date = new Date();
        for(ZsyhPlatformPartsattribute a:attList){//遍历规格信息赋值给会长产品规格
            String id = a.getId();
            BigDecimal price = map.get(id);
            ZsyhAgentPartsattribute attribute = ZsyhAgentPartsattribute.getInstance();
            attribute.setId(IdWorker.getId());
            attribute.setCreateTime(date);
            attribute.setAttributeName(a.getAttributeName());
            attribute.setAttributeSort(a.getAttributeSort());
            attribute.setAttributeSalePrice(price);
            attribute.setAttributeWarranty(a.getAttributeWarranty());
            attribute.setAttributeInstall(a.getAttributeInstall());
            attribute.setAttributePayPrice(a.getAttributePayPrice());
            attribute.setPartsId(partsIdNew);
            attribute.setAttributeFreeWarranty(a.getAttributeFreeWarranty());
            attribute.setAttributeRemarks(a.getAttributeRemarks());
            attribute.setAttributeLogo(a.getAttributeLogo());
            attribute.setIsPost(a.getIsPost());
            attribute.setIsShow("1");
//            attribute.setAttributeRetailPrice(a.getAttributeRetailPrice());
            attribute.setAttributeAdvantage(a.getAttributeAdvantage());
            attribute.setAttributeInstructions(a.getAttributeInstructions());

            arrList.add(attribute);
        }
        ZsyhAgentParts parts = new ZsyhAgentParts();//赋值产品信息给会长产品
        parts.setId(partsIdNew);
        parts.setAgentId(agentId);
        parts.setPartsName(p.getPartsName());
        parts.setPartsNumber(p.getPartsNumber());
        parts.setPartsType(p.getPartsType());
        parts.setPartsBrand(p.getPartsBrand());
        parts.setPartsDetails(p.getPartsDetails());
        parts.setPartsImages(p.getPartsImages());
        parts.setPartsRemarks(p.getPartsRemarks());
        parts.setIsTodayHot(p.getIsTodayHot());
        parts.setIsNewPush(p.getIsNewPush());
        parts.setIsGoodChoice(p.getIsGoodChoice());
        parts.setIsHotPush(p.getIsHotPush());
        parts.setIsPost(p.getIsPost());
        parts.setIsShow("1");
        parts.setPartsQuantity(p.getPartsQuantity());
        parts.setPartsSort(p.getPartsSort());
        parts.setPartsClassification(p.getPartsClassification());
        parts.setPartsUnit(p.getPartsUnit());
        parts.setPartsId(partsId);
        parts.setPartsDistinguish("1");
        parts.setPartsAttention(p.getPartsAttention());
        parts.setPartsInstructions(p.getPartsInstructions());

        parts.setZsyhAgentPartsattributeList(arrList);//产品规格
        zsyhAgentPartsService.insertZsyhAgentParts(parts);//保存
        return success("操作成功");


    }


    /**
     * 产品大全 根据分类查询产品列表 有平台产品，有会长产品
     * @param typeId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("/getPartsListByTypeId")
    @ResponseBody
    public AjaxResult getPartsListByTypeId(String userId, String typeId, String key , String pageNum, String pageSize){
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);
        String agentId = store.getAgentId();
        int num = Integer.valueOf(pageNum);
        int size = Integer.valueOf(pageSize);
        num = (num - 1) * size;
        List<Map> list = zsyhPlatformPartsService.getPartsListByTypeId(typeId, key, num, size, agentId);
        return AjaxResult.success("获取成功", list);
    }
}
